package com.daiziru.im.handle.impl;


import cn.hutool.json.JSONUtil;
import com.daiziru.common.constant.Constants;
import com.daiziru.im.handle.MsgHandler;
import com.daiziru.im.handle.filter.ExculdeMineChannelContextFilter;
import com.daiziru.im.message.ChatImMess;
import com.daiziru.im.message.ChatOutMess;
import com.daiziru.im.vo.ImMess;
import com.daiziru.im.vo.ImTo;
import com.daiziru.im.vo.ImUser;
import com.daiziru.service.ChatService;
import com.daiziru.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;

import java.util.Date;

/**
 * 发送消息的处理类型
 */
@Slf4j
public class ChatMsgHandler implements MsgHandler {

    @Override
    public void handler(String data, WsRequest wsRequest, ChannelContext channelContext) {
        //数据转化为对应的实体类
        ChatImMess chatImMess = JSONUtil.toBean(data, ChatImMess.class);
        ImUser mine = chatImMess.getMine();
        ImTo to = chatImMess.getTo();
        // 特殊处理？？

        ImMess imMess = new ImMess();
        imMess.setContent(mine.getContent());
        imMess.setAvatar(mine.getAvatar());
        imMess.setMine(false); // 是否是我发送的消息，我自己发送消息，对于群聊里的其他人来说，不是他自己发的，显示在群里聊的左边
        imMess.setUsername(mine.getUsername());
        imMess.setFromid(mine.getId());
        imMess.setId(Constants.IM_GROUP_ID);
        imMess.setTimestamp(new Date());
        imMess.setType(to.getType());

        ChatOutMess chatOutMess = new ChatOutMess();
        chatOutMess.setEmit("chatMessage");
        chatOutMess.setData(imMess);

        String result = JSONUtil.toJsonStr(chatOutMess);
        log.info("群聊消息----------> {}", result);
        //过滤不发送的人
        ExculdeMineChannelContextFilter filter = new ExculdeMineChannelContextFilter();
        filter.setCurrentContext(channelContext);

        //保存群聊信息
        ChatService chatService = (ChatService)SpringUtil.getBean("chatService");
        chatService.setGroupHistoryMsg(imMess);

        //返回数据到前端
        WsResponse wsResponse = WsResponse.fromText(result, "utf-8");
        Tio.sendToGroup(channelContext.getGroupContext(), Constants.IM_GROUP_NAME, wsResponse, filter);
    }
}
